/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 */
package com.lehe.service.impl;

import com.lehe.common.Contants;
import com.lehe.common.MessageEnumDto;
import com.lehe.common.crypt.Md5Encrypt;
import com.lehe.common.enums.GoldCoinEnum;
import com.lehe.common.exceptions.LHException;
import com.lehe.common.utils.StringUtil;
import com.lehe.dao.AgentInfoDao;
import com.lehe.dao.UserChargeGoldCoinLogDao;
import com.lehe.dao.UserManagerDao;
import com.lehe.dao.XHUserListDao;
import com.lehe.entry.AgentInfoDto;
import com.lehe.entry.UserChargeGoldCoinLogDto;
import com.lehe.entry.UserInfoDto;
import com.lehe.entry.xh.UserDto;
import com.lehe.wxpay.WXPay;
import com.lehe.wxpay.WXPayConfigImpl;
import com.lehe.wxpay.WXPayConstants;
import com.lehe.wxpay.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户代理操作
 *
 * @author 王丹
 * @since 2017-02-26
 */
@Transactional
@Service
public class AgentInfoService extends AbstractService {

    @Autowired
    private AgentInfoDao agentInfoDao;
    
    @Autowired
    private UserManagerDao userManagerDao;
    
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserChargeGoldCoinLogDao userChargeGoldCoinLogDao;
    
    @Autowired
    private XHUserListDao xHUserListDao;

    //private long[] whiteUserIds = {100734,120318,100540,100545,123181};

    /**
     * 新增一个代理
     * @param userId 父代理用户ID
     * @param agentSubInfoDto 子代理用户ID,手机号码,登录后台密码
     * @return
     */
    public MessageEnumDto createAgent(Long userId, Long childId){
        MessageEnumDto messageDto = MessageEnumDto.FAIL;
        List<UserDto> result = xHUserListDao.queryUserList(null,null,childId,null, null, null, null, null, null, null);
        if(result == null || result.isEmpty()){
        	messageDto.setMessageValue("授权的用户ID 不存在"+childId);
            return messageDto;
        }
        UserDto child = result.get(0);
        
        result = xHUserListDao.queryUserList(null,null,userId,null, null, null, null, null, null, null);
        if(result == null || result.isEmpty()){
        	messageDto.setMessageValue("父级ID 不存在"+userId);
            return messageDto;
        }
        UserDto parent = result.get(0);
        
        if(parent.getUtype() == 0){
            messageDto.setMessageValue("您不是代理");
            return messageDto;
        }
        
        if(child.getUtype() == 1){
            messageDto.setMessageValue("用户已经是代理,不需要重新授权！");
            return messageDto;
        }
       
        xHUserListDao.updateUserToAgent(childId);
        
        messageDto = MessageEnumDto.SUCCESS;
        return messageDto;
    }
    
    public MessageEnumDto passAgentApply(Long userId, Long childId){
        MessageEnumDto messageDto = MessageEnumDto.FAIL;
        List<UserDto> result = xHUserListDao.queryUserList(null,null,childId,null, null, null, null, null, null, null);
        if(result == null || result.isEmpty()){
        	messageDto.setMessageValue("授权的用户ID 不存在"+childId);
            return messageDto;
        }
        UserDto child = result.get(0);
        
        result = xHUserListDao.queryUserList(null,null,userId,null, null, null, null, null, null, null);
        if(result == null || result.isEmpty()){
        	messageDto.setMessageValue("父级ID 不存在"+userId);
            return messageDto;
        }
        UserDto parent = result.get(0);
        
        if(parent.getUtype() == 0){
            messageDto.setMessageValue("您不是代理");
            return messageDto;
        }
        
        if(child.getUtype() == 1){
            messageDto.setMessageValue("用户已经是代理,不需要重新授权！");
            return messageDto;
        }
        
        if(child.getParentId() == null || !child.getParentId().equals(userId)){
            messageDto.setMessageValue("用户不是您的下属玩家，不能授权");
            return messageDto;
        }
       
        xHUserListDao.updateUserToAgent(childId);
        
        xHUserListDao.updateApply(userId,childId);
        
        messageDto = MessageEnumDto.SUCCESS;
        return messageDto;
    }

    /**
     * 插入代理表数据
     * @param agentInfoDto
     * @return
     */
    public int insertAgentInfo(AgentInfoDto agentInfoDto){
        return agentInfoDao.insertAgentInfo(agentInfoDto);
    }

    /**
     * 给下属玩家充值
     * @param userId 充值的来源玩家
     * @param uid 充值的目标玩家
     * @param count 充值金额
     * @return
     */
	public MessageEnumDto charge(Long userId, Long uid, Integer count) {
		MessageEnumDto messageDto = MessageEnumDto.FAIL;
		
		if(count == null){
			messageDto.setMessageValue("请输入充值金额");
            return messageDto;
    	}
		
		if(userId == null){
			messageDto.setMessageValue("请输入充值来源玩家");
            return messageDto;
    	}
		
		if(uid == null){
			messageDto.setMessageValue("请输入充值目标玩家");
            return messageDto;
    	}

		//验证金币数够不够
    	UserInfoDto src = userInfoService.queryUserInfo(userId,null);
    	if(userId.equals(uid)){
    		messageDto.setMessageValue("不能给自己充值");
            return messageDto;
    	}
    	if(src == null){
    		messageDto.setMessageValue("充值的来源玩家不存在");
            return messageDto;
    	}
    	
    	
    	
    	if(count > (src.getGoldCoinCount() == null?0:src.getGoldCoinCount())){
    		messageDto.setMessageValue("你的金币数不足");
            return messageDto;
    	}
    	
    	
    	
    	UserInfoDto dest = userInfoService.queryUserInfo(uid,null);
    	if(dest == null){
    		messageDto.setMessageValue("要充值的目标玩家不存在");
            return messageDto;
    	}
        //boolean hasWhiteUser = Arrays.stream(whiteUserIds).anyMatch(whiteUserId -> userId == whiteUserId);
        boolean hasWhiteUser = userInfoService.hasWhiteUser(userId);
    	if(!hasWhiteUser){
    	    if(null!=dest.getAgentId() && dest.getAgentId()>0){
                messageDto.setMessageValue("代理之间不能互相转移金币");
                return messageDto;
            }
        }
    	
    	userManagerDao.chargeJB(userId,Long.valueOf(count*-1));
    	userManagerDao.chargeJB(uid,Long.valueOf(count));

        UserChargeGoldCoinLogDto userChargeGoldCoinLogDto = new UserChargeGoldCoinLogDto();
        userChargeGoldCoinLogDto.setJuniorUserId(uid);
        userChargeGoldCoinLogDto.setSuperiorUserId(src.getUserId());
        userChargeGoldCoinLogDto.setSuperiorAgentId(src.getAgentId());
        userChargeGoldCoinLogDto.setChargeCount(Long.valueOf(count));
        userChargeGoldCoinLogDto.setChargeMoney(0D);
        userChargeGoldCoinLogDto.setSourceType(Contants.USER_CHARGE_SOURCE_TYPE_WX);
        userChargeGoldCoinLogDto.setOpType(Contants.USER_CHARGE_OP_TYPE_ADD);
        userChargeGoldCoinLogDto.setCreateTime(LocalDateTime.now());
        userChargeGoldCoinLogDao.insert(userChargeGoldCoinLogDto);

    	messageDto = MessageEnumDto.SUCCESS;
        return messageDto;
	}

    public Map<String, String> confirmPay(Long userId, String wxOpenId, String goldLv, String remoteAddr) throws LHException {
        Map<String, String> retMap = new HashMap<>();
	    try {
            GoldCoinEnum goldCoinEnum = null;
            if (StringUtil.isNotBlank(goldLv)) {
                goldCoinEnum = GoldCoinEnum.valueOf(goldLv);
            }
            WXPayConfigImpl config = new WXPayConfigImpl();
            WXPay wxpay = new WXPay(config);
            //WXPay wxpay = new WXPay(config, WXPayConstants.SignType.MD5, true);
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", "代理购币数量-" + goldCoinEnum.getCoin());
            data.put("out_trade_no", StringUtil.getSerNo());
            data.put("device_info", "");
            data.put("fee_type", "CNY");
            data.put("total_fee", "1");
            //data.put("total_fee", String.valueOf(goldCoinEnum.getMoney()*100));
            data.put("spbill_create_ip", remoteAddr);
            data.put("notify_url", "http://wx.qpqpgame.com/index/wxpaynotify");
            data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
            data.put("openid", wxOpenId);
            data.put("product_id", goldLv);
            Map<String, String> resp = wxpay.unifiedOrder(data);
            if (WXPayUtil.isSuccess(resp)) {
                retMap.put("appId", config.getAppID());
                retMap.put("timeStamp", String.valueOf(System.currentTimeMillis()/1000));
                retMap.put("nonceStr", WXPayUtil.generateNonceStr());
                retMap.put("package", "prepay_id=" + resp.get("prepay_id"));
                retMap.put("signType", wxpay.getSignType().name());
                String paySign = WXPayUtil.generateSignature(retMap, config.getKey(), wxpay.getSignType());
                retMap.put("paySign", paySign);
                retMap.put("code", "1");
            } else {
                throw new LHException(resp.get("return_msg"));
            }
        }catch (LHException e){
            logger.error("充值失败业务异常", e);
            retMap.put("code", "0");
            retMap.put("msg", e.getMessage());
        } catch (Exception e){
	        logger.error("充值失败", e);
            retMap.put("code", "0");
            retMap.put("msg", "充值失败");
        }
        return retMap;
    }


}
